package utils;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Created by Liming on 2016/5/19.
 * 验证单元
 */
public class VerificationUtils {

    /**
     * 判断一个字符串是否是指定格式的日期
     * @param sDate
     * @param sDateFormat
     * @return
     */
    public boolean checkStrIsData(String sDate, String sDateFormat){
        boolean bResult = false;
        DateFormat dfDate = new SimpleDateFormat(sDateFormat);
        try {
            dfDate.parse(sDate);
            bResult = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return bResult;
    }

    /***
     * 判断身份证号码是否合法
     * @param sIdCardNum
     * @return
     */
    public boolean IdCardVerification(String sIdCardNum){
        boolean bResult = false;
        int iLength = sIdCardNum.trim().length();
        if((iLength == 15)||(iLength == 18))
        {
            String sDate = sIdCardNum.substring(6, 14);//判断是否日期
            bResult = checkStrIsData(sDate, "yyyyMMdd");
            if((iLength == 18) && (bResult)){
                int[] iWeight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; //权重
                char[] cReturn = { '1','0','X','9','8','7','6','5','4','3','2'};
                int iSum = 0;
                for (int i = 0; i < iLength - 1; i++) {
                    String sEvery = sIdCardNum.substring(i, i + 1);
                    if(StringUtils.isNumeric(sEvery)){
                        iSum = iSum + Integer.parseInt(sEvery) * iWeight[i];
                    }else{
                        bResult = false;
                        break;
                    }
                }
                int iMod = iSum % 11;

                bResult = sIdCardNum.substring(17).toUpperCase().equals(String.valueOf(cReturn[iMod]));
            }
        }
        return bResult;
    }
}
